package com.go.smsautosender.util;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.net.Uri;
import android.os.Handler;
import android.provider.MediaStore.Images.Media;
import android.telephony.TelephonyManager;
import android.util.Log;

import com.androidbridge.nokia.IMMConstants;
import com.androidbridge.nokia.MMContent;
import com.androidbridge.nokia.MMEncoder;
import com.androidbridge.nokia.MMMessage;
import com.androidbridge.nokia.MMResponse;
import com.androidbridge.nokia.MMSender;

public class MMS {
	private Context mContext = null;
	private Handler mHandler = null;
	
	private static final String TAG = "SendMMSActivity";

	private State mState;
	private boolean mListening;
	private boolean mSending;
	
	private BroadcastReceiver mReceiver = null;
	
	boolean[] mSK_flag = new boolean[2];
	
	public enum State {
		UNKNOWN,
		CONNECTED,
		NOT_CONNECTED
	}
	
	public MMS(Context context) {
		mContext = context;
		
		initBroadcast();
	}
	
	public MMS(Context context, Handler handler) {
		mContext = context;
		mHandler = handler;
		
		initBroadcast();
	}
	
	public void sendMMS(String phoneNum, Uri image, String message, int count)
	{
		MMMessage mm = new MMMessage();
		SetMessage(mm, phoneNum, count);
		AddContents(mm, image, message);
		MMEncoder encoder=new MMEncoder();
		encoder.setMessage(mm);

		try {
			encoder.encodeMessage();
			byte[] out = encoder.getMessage();

			MMSender sender = new MMSender();
				
			final String MMSCenterUrl = "http://mmsc.ktfwing.com:9082";
			final String MMSProxy = "alwayson.ktfwing.com";
			final String MMSPort = "9093";
			final Boolean  isProxySet =   (MMSProxy != null) && (MMSProxy.trim().length() != 0);			
			
			sender.setMMSCURL(MMSCenterUrl);
			sender.addHeader("MMS Massage", "100");

			MMResponse mmResponse = sender.send(out, isProxySet, MMSProxy, MMSPort);
			Log.d(TAG, "Message sent to " + sender.getMMSCURL());
			Log.d(TAG, "Response code: " + mmResponse.getResponseCode() + " " + mmResponse.getResponseMessage());
			
			Enumeration keys = mmResponse.getHeadersList();
			while (keys.hasMoreElements()){
				String key = (String) keys.nextElement();
				String value = (String) mmResponse.getHeaderValue(key);
				Log.d(TAG, (key + " : " + value));
			}

			if(mmResponse.getResponseCode() == 200)
			{
				// 200 Successful, disconnect and reset.
				mSending = false;
				mListening = false;
			}
			else
			{
				// kill dew :D hhaha
			}
		} catch (Exception e) {
			//System.out.println(e.getMessage());
			Log.e("MMS","",e);
		}
	}

	private void SetMessage(MMMessage mm, String phoneNum, int count) {
		if(!phoneNum.matches("[+][0-9]+")) {
			phoneNum = "+82" + phoneNum.substring(1);
		}
		phoneNum = phoneNum + "/TYPE=PLMN";
		
		String id = String.format("%010d", count);
		
		mm.setVersion(IMMConstants.MMS_VERSION_10);
		mm.setMessageType(IMMConstants.MESSAGE_TYPE_M_SEND_REQ);
		mm.setTransactionId(id);
		mm.setDate(new Date(System.currentTimeMillis()));
		mm.setFrom(phoneNum); // doesnt work, i wish this worked as it should be
		mm.addToAddress(phoneNum);
		mm.setDeliveryReport(true);
		mm.setReadReply(false);
		mm.setSenderVisibility(IMMConstants.SENDER_VISIBILITY_SHOW);
		mm.setSubject("");
		mm.setMessageClass(IMMConstants.MESSAGE_CLASS_PERSONAL);
		mm.setPriority(IMMConstants.PRIORITY_LOW);
		mm.setContentType(IMMConstants.CT_APPLICATION_MULTIPART_MIXED);
	}

	private void AddContents(MMMessage mm, Uri outputFileUri, String message) {
		/*Path where contents are stored*/

		// You need to have this file in your SD. Otherwise error..
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		Bitmap b;

		// Adds text content
		if(outputFileUri != null) {
			try {
				b = Media.getBitmap(mContext.getContentResolver(), outputFileUri);
				b.compress(CompressFormat.PNG, 90, os);
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				Log.e(TAG, "", e);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				Log.e(TAG, "", e);
			}
			
			MMContent part1 = new MMContent();
			byte[] buf1 = os.toByteArray();
			part1.setContent(buf1, 0, buf1.length);
			part1.setContentId("<0>");
			part1.setType(IMMConstants.CT_IMAGE_PNG);
			mm.addContent(part1);
		}
		
		if(message != null && !message.equals("")) {
			MMContent part2 = new MMContent();
			byte[] buf2 = message.getBytes();
			part2.setContent(buf2, 0, buf2.length);
			part2.setContentId("<1>");
			part2.setType(IMMConstants.CT_TEXT_PLAIN);
			mm.addContent(part2);
		}
	}
	
	public void unregisterReceiver() {
		mContext.unregisterReceiver(mReceiver);
	}
	
	private void initBroadcast() {
		mReceiver = new BroadcastReceiver() {
			
			@Override
			public void onReceive(Context context, Intent intent) {
				// TODO Auto-generated method stub

			}
		};
		
		try {
			String NON = ((TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE)).getNetworkOperatorName();
			IntentFilter mIntentFilter = new IntentFilter();
			
			if(NON.contains("SK")) {
				mIntentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
			}
			else {
				mIntentFilter.addAction("android.provider.Telephony.WAP_PUSH_RECEIVED");
				mIntentFilter.addDataType("application/vnd.wap.mms-message");
			}
			
		    mContext.registerReceiver(mReceiver, mIntentFilter);
		} catch(Exception e) {}
	}
}